const fs = require("fs");
const pkg = require("./package.json");
const env = process.argv[2];

const items = [["VITE_APP_VERSION", `VITE_APP_VERSION=${pkg.version}`]];
updateEnvFile(`.env.${env}`, items);

function updateEnvFile(envFilePath, items) {
  const fileContent = fs.readFileSync(envFilePath, "utf8");
  let updatedLines = fileContent.split("\n");
  items.forEach((item) => {
    const [key, value] = item;
    const exist = updatedLines.find((line) => line.startsWith(key));
    if (exist) {
      updatedLines = updatedLines.map((line) => (line.startsWith(key) ? value : line));
    } else {
      updatedLines = [...updatedLines, value];
    }
  });
  const updatedContent = updatedLines.join("\n");
  fs.writeFileSync(envFilePath, updatedContent);
}
